import React, { useState } from "react";
import style from "./style.module.scss";
import { Link, Prompt, withRouter } from "react-router-dom";
import toast from "../../UIcomponents/Toast/toast";

const Login = ({ history }) => {
  var init = {
    username: "",
    password: "",
    isauto: true,
    isput: false
  };
  if (localStorage.getItem("formstate")) {
    init = JSON.parse(localStorage.getItem("formstate"));
  }
  const [formstate, setFormstate] = useState(init);

  const handleChange = ev => {
    setFormstate({
      ...formstate,
      isput: ev.target.value.length > 0 ? true : false,
      [ev.target.name]: ev.target.value
    });
  };

  const handleCheck = ev => {
    setFormstate({
      ...formstate,
      [ev.target.name]: ev.target.checked
    });
  };

  const verRules = {
    username: value => value.length >= 3,
    password: value => value.length >= 6,
    isauto: () => true,
    isput: () => true
  };

  const verForm = () => {
    return Object.keys(formstate).every(name =>
      verRules[name](formstate[name])
    );
  };

  const handleSubmit = () => {
    const isSbumit = verForm();
    if (!isSbumit) {
      toast.error("请正确填写内容!");
      return;
    }
    if (formstate.isauto) {
      localStorage.setItem("formstate", JSON.stringify(formstate));
    }
    setFormstate({
      ...formstate,
      isput: false
    });
    toast.success("登陆成功!", 200, () => {
      history.push(`/`);
    });
  };

  return (
    <div className={style.login_warp}>
      <div className={style.login_container}>
        <div className={style.login_pages}>
          <h5>密码登录</h5>
          <ul>
            <li>
              <input
                onChange={ev => handleChange(ev)}
                name="username"
                type="text"
                placeholder="用户名"
                value={formstate.username}
              />
            </li>
            <li>
              <input
                onChange={ev => handleChange(ev)}
                name="password"
                type="password"
                placeholder="密码"
                value={formstate.password}
              />
            </li>
            <li>
              <input onClick={() => handleSubmit()} type="submit" />
            </li>
            <li className={style.auto_login}>
              <label>
                <input
                  onChange={ev => handleCheck(ev)}
                  name="isauto"
                  type="checkbox"
                  checked={formstate.isauto}
                />
                <span>下次自动登录</span>
              </label>
              <span>
                <Link to="/register">注册</Link>
              </span>
            </li>
          </ul>
        </div>
      </div>
      <Prompt when={formstate.isput} message="你确定要不提交就离开吗?" />
    </div>
  );
};

export default withRouter(Login);
